namespace Caliburn.Micro.Test
{
    #region Namespaces
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using Custom.Windows;

    #endregion

    public class AppBootstrapper : BootstrapperBase
    {
        #region Static Methods
        private static void OnStartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            MessageBox.Show(string.Format("Another application was launched with args:\n{0}", string.Join("\n", e.Args)));
        }
        #endregion

        #region Fields
        private SimpleContainer _container;
        #endregion

        public AppBootstrapper()
        {
            Start();
        }

        protected override void BuildUp(object instance)
        {
            _container.BuildUp(instance);
        }

        protected override void Configure()
        {
            _container = new SimpleContainer();

            _container.Singleton<IWindowManager, WindowManager>();
            _container.Singleton<IEventAggregator, EventAggregator>();
            _container.PerRequest<IShell, ShellViewModel>();
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.GetAllInstances(service);
        }

        protected override object GetInstance(Type service, string key)
        {
            var instance = _container.GetInstance(service, key);
            if (instance != null)
                return instance;

            throw new InvalidOperationException("Could not locate any instances.");
        }

        // ReSharper disable RedundantOverridenMember
        protected override void OnExit(object sender, EventArgs e)
        {
            base.OnExit(sender, e);
        }
        // ReSharper restore RedundantOverridenMember

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            var app = Application as InstanceAwareApplication;
            if (app == null || app.IsFirstInstance.GetValueOrDefault())
                DisplayRootViewFor<IShell>();
            else
                app.Shutdown();
        }

        protected override void PrepareApplication()
        {
            base.PrepareApplication();
            var application = (InstanceAwareApplication)Application;
            application.StartupNextInstance += OnStartupNextInstance;
        }
    }
}